package com.databaseconnectionmobilapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.databaseconnectionmobilapi.domain.dto.ChangeUserInfoDTO;
import com.databaseconnectionmobilapi.domain.dto.LoginDTO;
import com.databaseconnectionmobilapi.domain.dto.RegisterDTO;
import com.databaseconnectionmobilapi.domain.vo.LoginVO;
import com.databaseconnectionmobilapi.domain.vo.RegisterVO;
import com.databaseconnectionmobilapi.domain.entity.UserEntity;
import com.databaseconnectionmobilapi.mapper.UserMapper;
import com.databaseconnectionmobilapi.service.RedisService;
import com.databaseconnectionmobilapi.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.databaseconnectionmobilapi.util.result.RestResult;
import com.databaseconnectionmobilapi.util.util.StringUtil;
import com.databaseconnectionmobilapi.util.util.TokenUtil;
import com.databaseconnectionmobilapi.util.util.Tools;
import lombok.AllArgsConstructor;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.databaseconnectionmobilapi.constant.APIConstant.REST_RESULT_BUILDER;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fall
 * @since 2022-01-17
 */
@Service
@AllArgsConstructor
public class UserServiceImp extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    private UserMapper userMapper;
    private RedisService redisService;

    @Override
    public RestResult login(LoginDTO loginDto) {
        // 通过账号查询用户
        List<UserEntity> userEntityList = userMapper.selectList(new QueryWrapper<UserEntity>().eq("username", loginDto.getUsername()));

        if (userEntityList.size() == 0 || userEntityList.size() > 1) {
            return REST_RESULT_BUILDER.fail();
        }

        UserEntity user = userEntityList.get(0);

        // 判断密码是否正确
        if (loginDto.getPassword().equals(user.getPassword())) {
            String token = TokenUtil.getInstance().makeToken();

            LoginVO loginVO = LoginVO
                    .builder()
                    .token(token)
                    .color(user.getColor())
                    .build();

            redisService.set("userId" + user.getId(), token, 36000);
            redisService.set(token, "userId" + user.getId(), 36000);

            return REST_RESULT_BUILDER.success(loginVO);
        }

        return REST_RESULT_BUILDER.fail().setCode(401);
    }

    @Override
    public RestResult register(RegisterDTO registerDTO) {
        String salt = Tools.generateSalt();

        UserEntity userEntity = UserEntity
                .builder()
                .password(registerDTO.getPassword())
                .username(registerDTO.getUsername())
                .color("#1ce1e8")
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        save(userEntity);

        return REST_RESULT_BUILDER.success();
    }

    @Override
    public RestResult logout(String token) {
        String userId = redisService.get(token, String.class);

        redisService.remove(token);
        redisService.remove(userId);

        return REST_RESULT_BUILDER.success();
    }

    @Override
    public RestResult selectUserInfo(Integer userId) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .select("username", "avatar")
                .eq("id", userId);

        UserEntity userEntity = userMapper.selectOne(queryWrapper);

        return REST_RESULT_BUILDER.success(userEntity);
    }

    @Override
    public RestResult changeUserInfo(String token, ChangeUserInfoDTO changeUserInfoDTO) {
        UpdateWrapper<UserEntity> userEntityUpdateWrapper = new UpdateWrapper<>();

        Integer userId = StringUtil.getUserId(redisService.get(token, String.class));

        if (changeUserInfoDTO.getUsername() != null) {
            // 如果 username 不为空则需要更新
            userEntityUpdateWrapper.set("username", changeUserInfoDTO.getUsername()).eq("id", userId);
            update(userEntityUpdateWrapper);

            // 一般来说每次只会更新一个用户数据
            return REST_RESULT_BUILDER.success();
        }

        if (changeUserInfoDTO.getOldPassword() != null) {
            UserEntity userEntity = userMapper.selectById(userId);
            String password = userEntity.getPassword();
            if (!changeUserInfoDTO.getOldPassword().equals(password)) {
                return REST_RESULT_BUILDER.fail().setMsg("和旧有密码不一致");
            }

            userEntityUpdateWrapper.set("password", changeUserInfoDTO.getNewPassword()).eq("id", userId);
            update(userEntityUpdateWrapper);

            return REST_RESULT_BUILDER.success();
        }

        if (changeUserInfoDTO.getColor() != null) {
            userEntityUpdateWrapper.set("color", changeUserInfoDTO.getColor()).eq("id", userId);
            update(userEntityUpdateWrapper);

            return REST_RESULT_BUILDER.success();
        }

        return REST_RESULT_BUILDER.fail();
    }
}
